<?php
/************************FoxPHP威客系统************************/
/*                                                            */
/*  FoxPHP.Com (C)2006-2016 FoxPHP Inc.                       */
/*  This is NOT a freeware, use is subject to license terms   */
/*  FoxPHP威客系统是商业软件,使用于商业用途请购买授权         */
/*  V3.0 2016.3                                               */
/*  foxphp@aliyun.com                                         */
/*  http://www.foxphp.com                                     */
/*                                                            */
/**************************************************************/

namespace Login\Controller;
use Think\Controller;

@require_once(FOXPHP_PATH.'/Apps/Login/Class/Tencent.php');

class QqweiboController extends Controller {
	
	public function indexAction(){
		
		\OAuth::init(C('qqweiboappkey'),C('qqweiboappsecret'));
		 
		$url = \OAuth::getAuthorizeURL(C('S_URL').'/login/qqweibo/callback');
		 
		header("location:$url");
	}
	
	public function callbackAction(){
		if ($_SESSION['t_access_token'] || ($_SESSION['t_openid'] && $_SESSION['t_openkey'])) {//已授权
			$user = json_decode(\Tencent::api('user/info'),true);
			if($user){
				$weibo=new \Member\Model\MemberModel();
				if($weibo->LoginWeiBo(array('type'=>2,'apikey'=>$_SESSION['t_access_token'],'apiname'=>$user['name'],'followers'=>$user['fansnum']))){
					if($this->uid){
						$this->error('绑定成功！','/',3);
					}else{
						$this->error('登录成功！','/',3);
					}
				}else{
					$this->error('认证失败！！！','/',3);
					return false;
				}
			}
		}else{
			if($_GET['code']) {//已获得code
				$code = $_GET['code'];
				$openid = $_GET['openid'];
				$openkey = $_GET['openkey'];
				//获取授权token
				$url = \OAuth::getAccessToken($code,C('S_URL').'/login/qqweibo/callback');
				$r = \Http::request($url);
				parse_str($r, $out);
				//存储授权数据
				if ($out['access_token']) {
					$_SESSION['t_access_token'] = $out['access_token'];
					$_SESSION['t_refresh_token'] = $out['refresh_token'];
					$_SESSION['t_expire_in'] = $out['expire_in'];
					$_SESSION['t_code'] = $code;
					$_SESSION['t_openid'] = $openid;
					$_SESSION['t_openkey'] = $openkey;

					//验证授权
					$r = \OAuth::checkOAuthValid();
					if($r){
						header('Location: '.C('S_URL').'/login/qqweibo/callback');
					}else{
						$this->error('认证失败！！','/',3);
						return false;
					}
				}else{
					$this->error('认证失败！！','/',3);
					return false;
				}
			}else{
				$this->error('认证失败！','/',3);
				return false;
			}
		}
	}
}